package cn.edu.bit.lixin.blog.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.bit.lixin.blog.entity.User;

//implments的这个Filter属于javax.servlet.filter
public class SecurityFilter implements Filter {
	private ServletContext servletContext;

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse) resp;
		User currentUser = (User)request.getSession().getAttribute("loginedUser");
		
		//如果用户没有登录则跳转到登录页面
		if (currentUser == null){
			response.sendRedirect("/blog/login.jsp");	
		}else{
			//如果用户已经登录，那么继续前进
			chain.doFilter(req, resp);
		}
	}

	public void init(FilterConfig config) throws ServletException {
		servletContext = config.getServletContext();
	}

}
